import { defineStore } from 'pinia';

const menuRoutes = [
  {
    path: '/admin',
    name: 'dashboard',
    children: [],
    meta: {
      title: '仪表盘',
      en_title: 'Dashboard',
      icon: 'monitor',
      affix: true,
    }
  },
  // {
  //   path: '/admin/system/user',
  //   name: 'system',
  //   meta: {
  //     title: '系统管理',
  //     en_title: 'System Management',
  //     icon: 'setting'
  //   },
  //   children: [
  //     {
  //       path: '/admin/system/user',
  //       name: 'user',
  //       meta: {
  //         title: '用户管理',
  //         en_title: 'User Management',
  //         icon: 'user'
  //       },
  //       children: []
  //     },
  //     {
  //       path: '/admin/system/role',
  //       name: 'team',
  //       meta: {
  //         title: '角色管理',
  //         en_title: 'Role Management',
  //         icon: 'team'
  //       },
  //       children: []
  //     },
  //     {
  //       path: '/admin/system/menu',
  //       name: 'menu',
  //       meta: {
  //         title: '菜单管理',
  //         en_title: 'Menu Management',
  //         icon: 'menu'
  //       },
  //       children: []
  //     },
  //     {
  //       path: '/admin/system/dept',
  //       name: 'user',
  //       meta: {
  //         title: '部门管理',
  //         en_title: 'Department Management',
  //         icon: 'cluster'
  //       },
  //       children: []
  //     },
  //     {
  //       path: '/admin/system/post',
  //       name: 'post',
  //       meta: {
  //         title: '岗位管理',
  //         en_title: 'Post Management',
  //         icon: 'addteam'
  //       },
  //       children: []
  //     }
  //   ],
  // }
];

const formatBreadcrumbs = (routes: any[]) => {
  const breadcrumbs: any[] = [];

  const traverse = (routes: any[], parent: any = null) => {
    routes.forEach(route => {
      const breadcrumb = {
        ...route.meta,
        path: route.path,
        parent: parent
      };
      breadcrumbs.push(breadcrumb);

      if (route.children && route.children.length > 0) {
        traverse(route.children, breadcrumb);
      }
    });
  };

  traverse(routes);

  return breadcrumbs;
};

export const routerStore = defineStore('routerStore', {
	state: () => ({
		routes: menuRoutes,
	}),
	actions: {
    getBreadcrumbs(path: string) {
      const breadcrumbs = formatBreadcrumbs(this.routes);
      let data: any = breadcrumbs.find((item: any) => item.path === path);
      const result = [];

      while (true) {
        result.unshift(data);
        if (data?.parent) {
          data = data.parent;
        } else {
          break;
        }
      }

      return result;
    },
		setRoutes(routers: []) {
			this.routes = routers
		},
    initRoutes(routes: []) {
      const menus = menuRoutes.concat(routes);
      this.routes = menus;
    },
	},
  persist: true,
})
